< previous page page_461 next page >

Page 461
You can also use the SendMessage and PostMessage API calls to send Windows messages to a window. For example, the following line would cause Notepad to close as if you had ended it from the Windows Task Manager:
lRetVal = SendMessage(hwndNotepad, WM_CLOSE, 0&, 0&)
The preceding line of code causes Windows to send the WM_CLOSE message to the specified window. Upon receiving the message, Notepad exits, possibly prompting the user to save an open document. The PostMessage API has the same syntax as SendMessage, with the important distinction that it works asynchronously, meaning it does not wait until the message has been processed before continuing.
In the example, notice that the last two parameters are zeros because they are specific to an individual message and WM_CLOSE does not use them. For example, if you use a WM_CHAR message to send a character, these last two parameters are used to specify the character. Remember that you can send literally hundreds of messages, each with its own purpose.
CAUTION
Although the examples shown here are relatively safe when used with Notepad, other programs may react undesirably, causing errors. For the best results when using the Windows API with other windows, (1) read and understand the documentation for the API and/or Windows message, (2) make sure you are working with the right window, and (3) be prepared to reboot a lot.

Waiting on a Program to Finish Running
Sometimes you may need to launch other programs from within VB. Visual Basic has a built-in function to do so, Shell, which is covered in Chapter 21, "Working with Files."
sarrow.gifSee ''Launching Other Programs with the Shell Function," p. 475
However, the drawback of using Shell is that it does not wait for the shelled program to finish running before executing the next line of code:
'THIS DOES NOT WORK!!!
dRetVal = Shell("MyBat.Bat")
MsgBox "Batch file complete!"
The preceding lines of code do not have the intended result. The message box appears as soon as the Shell function is executed, whether the batch file is finished or not. In the 16-bit world of Windows 3.11 and Visual Basic 3.0, this problem was easy to get around with a few lines of code and two API calls. However, in the 32-bit world, things are a lot more complicated. In-depth coverage of 32-bit processes and threads would probably require half a book. Rather than go into that much detail, I will briefly describe a function to accomplish this task, from Microsoft Knowledge Base article Q129796. A function adapted from this example is shown in Listing 20.7.

 
< previous page page_461 next page >